package queue;

/**
 * 循环队列：
 * 思路：https://blog.csdn.net/weixin_44187730/article/details/96141225
 * https://blog.csdn.net/qq_26356861/article/details/115386230
 * @param <T>
 */
public class CircleQueue<T> {
    private int size;
    private int front;
    private int rear;
    private Object[] array;
    public CircleQueue(){
        size = 0;
        front = 0;
        rear = 0;
    }
    public CircleQueue(int size){
        this.size = size;
        front = 0;
        rear = 0;
        array = new Object[size];
    }
    public boolean isFull(){
        return (rear+1-front)%size==0;
    }
    public boolean isEmpty(){
        return rear==front;
    }
    public void add(T element) throws Exception {
        if (isFull()){
            throw new Exception("queue is full");
        }
        array[rear] = element;
        rear = (rear+1)%size;
    }
    public T pop() throws Exception {
        checkRange();
        T data = (T) array[front];
        front = (front+1)%size;
        return data;
    }
    public int getSize(){
        return (rear+size-front)%size;
    }
    public void displayQueue() throws Exception {
        checkRange();
        int size = this.getSize();
        for(int i = front;i<front+size;i++){
            System.out.println("array["+i%size+"] = "+array[i%size]);
        }
    }
    public T getHead() throws Exception {
        checkRange();
        return (T) array[front];
    }

    private void checkRange() throws Exception{
        if(isEmpty()){
            throw new Exception("queue is empty");
        }
    }





}
